import store from '../store'

const webSqlUtil = require('./webSqlUtil')

let isDropTable = false
let isInitTable = false

/**
 * 创建用户表
 * userip 用户ip
 * xm 姓名
 * tx 头像
 * qm 签名
 * zt 状态
 * mac mac地址
 * dnm 电脑名
 * @returns {Promise<any>}
 */
export function createTable () {
  return webSqlUtil.run(`create table if not exists user(
      userip text, 
      xm text,
      tx text,
      qm text,
      zt text,
      mac text,
      dnm text
    )`)
}

export function dropTable () {
  return webSqlUtil.run(`drop table if exists user`)
}

export async function initTable () {
  if (isDropTable) {
    isDropTable = false
    await dropTable()
  }
  await createTable()
  if (!isInitTable) {
    isInitTable = true
    await webSqlUtil.run(`update user set zt=?`, ['offline'])
  }
  return ''
}

// 增加用户
export async function addUser ($user = {}) {
  await initTable()
  let {userip, xm, tx, qm, zt, mac, dnm} = $user
  let user = await getUser(userip)
  if (!user) {
    console.log('添加用户', $user)
    store.dispatch('addUser', $user)
    return webSqlUtil.run(`insert into user(userip,xm,tx,qm,zt,mac,dnm) values(?,?,?,?,?,?,?)`, [userip, xm, tx, qm, zt, mac, dnm])
  } else {
    return updateUser($user)
  }
}

// 删除用户

// 修改用户
export async function updateUser ($user = {}) {
  await initTable()
  let {userip, xm, tx, qm, zt, mac, dnm} = $user
  console.log('修改', $user)
  store.dispatch('updateUser', $user)
  return webSqlUtil.run(`update user set xm=?,tx=?,qm=?,zt=?,mac=?,dnm=? where userip=?`, [xm, tx, qm, zt, mac, dnm, userip])
}

// 查询用户
export async function getUser (userip) {
  let users = await getUsers(userip)
  if (users.length) return users[0]
  return null
}

export async function getUsers (userip) {
  await initTable()
  let condition = ''
  let param = []
  if (userip !== undefined) {
    condition = `and userip=?`
    param.push(userip)
  }
  return webSqlUtil.run(`select * from user where 1=1 ${condition}`, param)
}
